/**
 * 依赖类
 */
import tnx from '@/tnx.js';
import BaseType from './BaseType.js';
import EntityClass from './EntityClass.js';
import ModelingClass from './ModelingClass.js';

export default class DependencyClass {

    /**
     * 原始类
     * @type {BaseType}
     */
    origin = null;
    /**
     * 引用类的最近保存时间
     * @type {Date}
     */
    lastSaveTime = null;
    /**
     * 偏爱序号，大于0才视为偏爱
     * @type {number}
     */
    favoriteOrdinal = 0;
    deprecated = false;
    referencedNum = 0;

    constructor(origin) {
        if (origin instanceof BaseType) {
            this.origin = origin;
        } else if (origin && typeof origin === 'object') {
            this.origin = BaseType.of(origin);
        } else {
            throw new Error('The origin is not a BaseType');
        }
    }

    static of(object) {
        if (typeof object !== 'object') {
            return undefined;
        }
        let clazz = new DependencyClass(object.origin);
        clazz.update(object);
        return clazz;
    }

    update(object) {
        // 只覆写简单字段，所以origin不会覆写，也不该覆写
        return tnx.util.object.rewriteSimpleDefined(this, object);
    }

    clone() {
        return DependencyClass.of(this);
    }

    getId() {
        return this.origin ? this.origin.id : '';
    }

    getKind() {
        return this.origin ? this.origin.kind : undefined;
    }

    getPackageName() {
        return this.origin ? this.origin.packageName : '';
    }

    getSimpleName() {
        return this.origin ? this.origin.simpleName : '';
    }

    getName() {
        return this.origin ? this.origin.getName() : '';
    }

    isPrimitive() {
        return this.origin && this.origin.isPrimitive();
    }

    isFinal() {
        return this.origin && this.origin.isFinal();
    }

    matches(object) {
        return this.origin && this.origin.matches(object);
    }

    getPrimaryLogicTypeIds(toPrimitive) {
        if (this.origin && this.origin instanceof EntityClass) {
            return this.origin.getPrimaryLogicTypeIds(toPrimitive);
        }
        return [];
    }

    /**
     * 判断是否需要同步
     * @return {boolean} 是否需要同步
     */
    needsSync() {
        return this.origin instanceof ModelingClass && this.lastSaveTime && this.lastSaveTime > this.origin.saveTime;
    }

}
